<template>
  <div class="project-members-container" v-loading="loading">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/projects' }">项目管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/projects/${projectId}` }">
            {{ projectName }}
          </el-breadcrumb-item>
          <el-breadcrumb-item>成员管理</el-breadcrumb-item>
        </el-breadcrumb>
        
        <h1 class="page-title">项目成员管理</h1>
        <p class="page-description">管理项目团队成员，分配角色和权限</p>
      </div>
      
      <div class="header-right">
        <el-button 
          v-if="canManageMembers"
          type="primary" 
          @click="showAddMemberDialog"
        >
          <el-icon><Plus /></el-icon>
          添加成员
        </el-button>
      </div>
    </div>

    <!-- 成员统计卡片 -->
    <div class="members-stats">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ memberStats.total }}</div>
              <div class="stats-label">总成员数</div>
            </div>
            <el-icon class="stats-icon"><UserFilled /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ memberStats.owners }}</div>
              <div class="stats-label">项目负责人</div>
            </div>
            <el-icon class="stats-icon owner"><UserFilled /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ memberStats.admins }}</div>
              <div class="stats-label">管理员</div>
            </div>
            <el-icon class="stats-icon admin"><UserFilled /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ memberStats.members }}</div>
              <div class="stats-label">普通成员</div>
            </div>
            <el-icon class="stats-icon member"><UserFilled /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 成员列表 -->
    <el-card class="members-card">
      <template #header>
        <div class="card-header">
          <span>项目成员 ({{ members.length }})</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索成员..."
              style="width: 200px"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="roleFilter"
              placeholder="筛选角色"
              style="width: 120px"
              clearable
              @change="handleRoleFilter"
            >
              <el-option label="全部" value="" />
              <el-option label="负责人" value="owner" />
              <el-option label="管理员" value="admin" />
              <el-option label="成员" value="member" />
              <el-option label="查看者" value="viewer" />
            </el-select>
          </div>
        </div>
      </template>

      <div class="members-list">
        <div 
          v-for="(member, index) in filteredMembers" 
          :key="member.user_id || index"
          class="member-item"
        >
          <div class="member-info">
            <UserDisplay
              :userId="member.user_id"
              :userName="member.user_name"
              :userAvatar="member.user_avatar"
              :size="'medium'"
              :showAvatar="true"
            />
            <div class="member-details">
              <div class="member-email">{{ member.user_email || '未设置邮箱' }}</div>
              <div class="member-meta">
                <div class="member-roles">
                  <el-tag
                    v-if="member.role"
                    :type="getRoleTagType(member.role) as any"
                    size="small"
                    style="margin-right: 4px;"
                  >
                    {{ getRoleName(member.role) }}
                  </el-tag>
                  <span v-if="!member.role" class="no-role">未分配角色</span>
                </div>
                <span class="join-time">
                  加入时间：{{ formatDateTime(member.joined_at) }}
                </span>
              </div>
            </div>
          </div>
          
          <!-- 权限显示已移除，因为 ProjectMember 接口中没有 permissions 字段 -->
          
          <div v-if="canManageMembers" class="member-actions">
            <el-button 
              size="small" 
              @click="handleEditMember(member)"
              :disabled="!canEditMember(member)"
            >
              编辑
            </el-button>
            <el-dropdown 
              @command="(command) => handleMemberAction(command, member)"
              :disabled="!canManageMember(member)"
            >
              <el-button size="small">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="changeRole">更改角色</el-dropdown-item>
                  <el-dropdown-item command="permissions">权限设置</el-dropdown-item>
                  <el-dropdown-item command="remove" divided>移除成员</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <div v-if="filteredMembers.length === 0" class="empty-members">
          <el-empty description="暂无成员" :image-size="80" />
        </div>
      </div>
    </el-card>

    <!-- 添加成员对话框 -->
    <el-dialog
      v-model="addMemberDialogVisible"
      title="添加项目成员"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addMemberFormRef"
        :model="addMemberForm"
        :rules="addMemberRules"
        label-width="80px"
      >
        <el-form-item label="用户" prop="user_id">
          <el-select
            v-model="addMemberForm.user_id"
            placeholder="从用户列表中选择"
            style="width: 100%"
            filterable
            :loading="allUsersLoading"
          >
            <el-option
              v-for="user in nonMemberUsers"
              :key="user.id"
              :label="user.name || user.username || user.email"
              :value="user.id"
            >
              <UserDisplay
                :user="user"
                :show-avatar="true"
                size="small"
              />
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="角色" prop="roles">
          <el-select 
            v-model="addMemberForm.roles" 
            placeholder="选择角色（可多选）" 
            style="width: 100%"
            multiple
            filterable
          >
            <el-option
              v-for="role in projectRoles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            >
              <span>{{ role.name }}</span>
              <span style="color: #8492a6; font-size: 13px; margin-left: 8px;">
                {{ role.description || role.code }}
              </span>
            </el-option>
          </el-select>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            可以为成员分配多个项目角色
          </div>
        </el-form-item>
        
        <!-- 权限配置已移除，因为 addProjectMember API 不支持 permissions 参数 -->
      </el-form>
      
      <template #footer>
        <el-button @click="addMemberDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddMember" :loading="addMemberLoading">
          添加
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑成员对话框 -->
    <el-dialog
      v-model="editMemberDialogVisible"
      title="编辑成员信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editMemberFormRef"
        :model="editMemberForm"
        :rules="editMemberRules"
        label-width="80px"
      >
        <el-form-item label="用户">
          <div class="user-info">
            <UserDisplay
              :userId="editMemberForm.user_id"
              :userName="editMemberForm.user_name"
              :size="'small'"
              :showAvatar="true"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="角色" prop="roles">
          <el-select 
            v-model="editMemberForm.roles" 
            placeholder="选择角色（可多选）" 
            style="width: 100%"
            multiple
            filterable
          >
            <el-option
              v-for="role in projectRoles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            >
              <span>{{ role.name }}</span>
              <span style="color: #8492a6; font-size: 13px; margin-left: 8px;">
                {{ role.description || role.code }}
              </span>
            </el-option>
          </el-select>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            可以为成员分配多个项目角色
          </div>
        </el-form-item>
        
        <el-form-item label="权限" prop="permissions">
          <el-checkbox-group v-model="editMemberForm.permissions">
            <el-checkbox label="project:read">查看</el-checkbox>
            <el-checkbox label="project:write">编辑</el-checkbox>
            <el-checkbox label="project:delete">删除</el-checkbox>
            <el-checkbox label="project:manage_members">管理成员</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editMemberDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateMember" :loading="updateMemberLoading">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus, UserFilled, Search, ArrowDown } from '@element-plus/icons-vue'
import UserDisplay from '@/components/ui/UserDisplay.vue'
import { 
  getProjectMembers, 
  addProjectMember, 
  updateProjectMember, 
  removeProjectMember,
  type ProjectMember,
  ProjectRole
} from '@/api/project'
import { getUsers } from '@/api/user';
import type { User } from '@/api/user'
import { getRoles, type Role } from '@/api/roles'
import { usePermission } from '@/hooks/usePermission'

// 路由
const route = useRoute()
const router = useRouter()

// 权限检查
const { hasPermission, hasRole } = usePermission()

// 检查是否有成员管理权限（管理员或项目管理员）
const canManageMembers = computed(() => {
  // 检查权限
  if (hasPermission('project:manage_members') || hasPermission('PROJECT_MANAGE_MEMBERS')) {
    return true
  }
  // 检查角色：管理员或项目管理员
  if (hasRole('admin') || hasRole('project_manager')) {
    return true
  }
  return false
})

// 响应式数据
const loading = ref(false)
const projectId = computed(() => route.params.id as string)
const projectName = ref('项目名称')

// 成员数据
const members = ref<ProjectMember[]>([])
const searchKeyword = ref('')
const roleFilter = ref('')

// 权限检查：如果没有权限，重定向到项目详情页
onMounted(() => {
  if (!canManageMembers.value) {
    ElMessage.warning('您没有访问项目成员管理页面的权限')
    router.replace(`/projects/${projectId.value}`)
  }
})

// 成员统计
const memberStats = computed(() => {
  const stats = {
    total: members.value.length,
    owners: 0,
    admins: 0,
    members: 0,
    viewers: 0
  }
  
  members.value.forEach((member: ProjectMember) => {
    switch (member.role) {
      case 'owner':
        stats.owners++
        break
      case 'manager':
        stats.admins++
        break
      case 'developer':
      case 'tester':
        stats.members++
        break
      case 'viewer':
        stats.viewers++
        break
    }
  })
  
  return stats
})

// 过滤后的成员列表
const filteredMembers = computed(() => {
  let filtered = members.value
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter((member: ProjectMember) => {
      const name = (member.user_name || '').toLowerCase()
      const email = (member.user_email || '').toLowerCase()
      return name.includes(keyword) || email.includes(keyword)
    })
  }
  
  // 按角色筛选
  if (roleFilter.value) {
    filtered = filtered.filter((member: ProjectMember) => member.role === roleFilter.value)
  }
  
  return filtered
})

// 项目角色列表
const projectRoles = ref<Role[]>([])
const projectRolesLoading = ref(false)

// 添加成员对话框
const addMemberDialogVisible = ref(false)
const addMemberLoading = ref(false)
const addMemberFormRef = ref<FormInstance>()
const addMemberForm = reactive({
  user_id: '',
  roles: [] as string[] // 项目角色ID列表
})

const addMemberRules = {
  user_id: [{ required: true, message: '请选择用户', trigger: 'change' }],
  roles: [{ required: true, message: '请至少选择一个角色', trigger: 'change', type: 'array' as const, min: 1 }]
}

// 编辑成员对话框
const editMemberDialogVisible = ref(false)
const updateMemberLoading = ref(false)
const editMemberFormRef = ref<FormInstance>()
const editMemberForm = reactive({
  user_id: '',
  user_name: '',
  roles: [] as string[], // 项目角色ID列表
  permissions: ['project:read']
})

const editMemberRules = {
  roles: [{ required: true, message: '请至少选择一个角色', trigger: 'change', type: 'array' as const, min: 1 }]
}

// 用户列表
const allUsers = ref<User[]>([])
const allUsersLoading = ref(false)
const nonMemberUsers = computed(() => {
  const memberIds = new Set(members.value.map((m: ProjectMember) => m.user_id))
  return allUsers.value.filter(u => u.id && !memberIds.has(u.id))
})


// 获取项目成员
const fetchProjectMembers = async () => {
  if (!projectId.value) return
  
  loading.value = true
  try {
    const response = await getProjectMembers(projectId.value)
    const payload = response?.data
    // 处理不同的响应格式：可能是数组，也可能是包含 members 字段的对象
    const membersArray = Array.isArray(payload)
      ? payload
      : (payload && typeof payload === 'object' && 'members' in payload && Array.isArray((payload as any).members))
        ? (payload as any).members
        : []
    
    members.value = membersArray
    // 如果需要项目名称，需要从其他地方获取或从响应中提取
  } catch (error) {
    console.error('获取项目成员失败:', error)
    ElMessage.error('获取项目成员失败')
    members.value = []
  } finally {
    loading.value = false
  }
}

// 加载项目角色列表
const loadProjectRoles = async () => {
  projectRolesLoading.value = true
  try {
    const roles = await getRoles('project') // 只获取项目角色
    projectRoles.value = roles.filter(role => role.is_active) // 只显示激活的角色
  } catch (error) {
    console.error('获取项目角色列表失败:', error)
    ElMessage.error('获取项目角色列表失败')
    projectRoles.value = []
  } finally {
    projectRolesLoading.value = false
  }
}

// 加载所有用户
const loadAllUsers = async () => {
  allUsersLoading.value = true
  try {
    // Assuming getUsers returns an object with an 'items' array
    const response = await getUsers({ size: 200 })
    if (response && 'items' in response && Array.isArray(response.items)) {
      allUsers.value = response.items as User[]
    } else {
      allUsers.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    allUsersLoading.value = false
  }
}

// 显示添加成员对话框
const showAddMemberDialog = () => {
  addMemberForm.user_id = ''
  addMemberForm.roles = []
  loadAllUsers()
  loadProjectRoles()
  addMemberDialogVisible.value = true
}

// 添加成员
const handleAddMember = async () => {
  if (!addMemberFormRef.value) return
  
  try {
    await addMemberFormRef.value.validate()
    addMemberLoading.value = true
    
    await addProjectMember(projectId.value, {
      user_id: addMemberForm.user_id,
      roles: addMemberForm.roles
    })
    
    ElMessage.success('成功添加成员')
    addMemberDialogVisible.value = false
    await fetchProjectMembers()
  } catch (error: any) {
    if (error !== false) { // 不是表单验证错误
      console.error('添加成员失败:', error)
      ElMessage.error(error?.message || '添加成员失败')
    }
  } finally {
    addMemberLoading.value = false
  }
}

// 编辑成员
const handleEditMember = async (member: ProjectMember) => {
  editMemberForm.user_id = member.user_id
  editMemberForm.user_name = member.user_name || ''
  // 从 role 转换为数组（项目成员只有一个角色）
  editMemberForm.roles = member.role ? [member.role] : []
  editMemberForm.permissions = ['project:read'] // 项目成员没有单独的权限字段
  
  // 确保项目角色列表已加载
  if (projectRoles.value.length === 0) {
    await loadProjectRoles()
  }
  
  editMemberDialogVisible.value = true
}

// 更新成员
const handleUpdateMember = async () => {
  if (!editMemberFormRef.value) return
  
  try {
    await editMemberFormRef.value.validate()
    updateMemberLoading.value = true
    
    await updateProjectMember(projectId.value, editMemberForm.user_id, {
      roles: editMemberForm.roles,
      permissions: editMemberForm.permissions
    })
    
    ElMessage.success('成员信息更新成功')
    editMemberDialogVisible.value = false
    await fetchProjectMembers()
  } catch (error) {
    if (error !== false) {
      console.error('更新成员失败:', error)
      ElMessage.error('更新成员失败')
    }
  } finally {
    updateMemberLoading.value = false
  }
}

// 成员操作
const handleMemberAction = async (command: string, member: ProjectMember) => {
  switch (command) {
    case 'changeRole':
    case 'permissions':
      handleEditMember(member)
      break
    case 'remove':
      try {
        await ElMessageBox.confirm(
          `确定要移除成员 "${member.user_name || '该成员'}" 吗？`,
          '确认移除',
          { type: 'warning' }
        )
        
        await removeProjectMember(projectId.value, member.user_id)
        ElMessage.success('成员移除成功')
        await fetchProjectMembers()
      } catch (error) {
        if (error === 'cancel') {
          return
        }
        console.error('移除成员失败:', error)
        const errorMessage = '无法移除项目创建者'
        ElMessage.error(errorMessage)
      }
      break
  }
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// 角色筛选处理
const handleRoleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

// 权限检查
const canEditMember = (member: ProjectMember) => {
  // 简化权限检查，实际应该根据当前用户权限判断
  return member.role !== ProjectRole.OWNER
}

const canManageMember = (member: ProjectMember) => {
  // 简化权限检查，实际应该根据当前用户权限判断
  return member.role !== ProjectRole.OWNER
}

// 工具函数：根据角色ID获取角色名称
const getRoleName = (roleId: string): string => {
  // 如果是旧的 role 代码（向后兼容）
  const oldRoleMap: Record<string, string> = {
    owner: '项目负责人',
    manager: '管理员',
    developer: '开发人员',
    tester: '测试人员',
    designer: '设计师',
    analyst: '分析师',
    viewer: '查看者'
  }
  if (oldRoleMap[roleId]) {
    return oldRoleMap[roleId]
  }
  
  // 从项目角色列表中查找
  const role = projectRoles.value.find(r => r.id === roleId)
  return role?.name || roleId
}

// 工具函数：根据角色ID获取标签类型
const getRoleTagType = (roleId: string): string => {
  // 如果是旧的 role 代码（向后兼容）
  const oldRoleTypeMap: Record<string, string> = {
    owner: 'danger',
    manager: 'warning',
    developer: 'primary',
    tester: 'success',
    designer: 'primary',
    analyst: 'primary',
    viewer: 'info'
  }
  if (oldRoleTypeMap[roleId]) {
    return oldRoleTypeMap[roleId]
  }
  
  // 默认类型
  return 'info'
}


// 权限文本映射（已注释，因为 ProjectMember 接口中没有 permissions 字段）
// const getPermissionText = (permission: string) => {
//   const permissionMap: Record<string, string> = {
//     'project:read': '查看',
//     'project:update': '编辑',
//     'project:delete': '删除',
//     'project:manage_members': '管理成员'
//   }
//   return permissionMap[permission] || permission
// }

const formatDateTime = (datetime: string | undefined) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchProjectMembers()
  loadProjectRoles() // 加载项目角色列表
})
</script>

<style scoped>
.project-members-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 16px 0 8px 0;
}

.page-description {
  color: #6b7280;
  font-size: 14px;
  margin: 0;
}

.header-right {
  display: flex;
  gap: 12px;
}

.members-stats {
  margin-bottom: 24px;
}

.stats-card {
  position: relative;
  overflow: hidden;
}

.stats-content {
  position: relative;
  z-index: 2;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 8px;
}

.stats-icon {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 40px;
  opacity: 0.1;
  z-index: 1;
}

.stats-icon.owner {
  color: #ef4444;
}

.stats-icon.admin {
  color: #f59e0b;
}

.stats-icon.member {
  color: #10b981;
}

.members-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.members-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.member-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  transition: all 0.2s;
}

.member-item:hover {
  border-color: #d1d5db;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.member-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex: 1;
}

.member-details {
  flex: 1;
  margin-left: 0;
}

.member-email {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.member-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.join-time {
  font-size: 12px;
  color: #9ca3af;
}

.member-permissions {
  flex: 1;
  margin-left: 16px;
}

.permissions-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.permissions-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.permission-tag {
  margin: 0;
}

.member-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.empty-members {
  padding: 40px;
  text-align: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .project-members-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .member-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .member-permissions {
    margin-left: 0;
    margin-top: 12px;
  }
  
  .member-actions {
    justify-content: flex-end;
    margin-top: 12px;
  }
}

/* 确保 el-select 选项中的 UserDisplay 组件正确显示 */
:deep(.el-select-dropdown__item) {
  .user-display {
    width: 100%;
    display: flex;
    align-items: center;
    gap: 8px;
  }
}
</style>
